<template>
  <div class="financial-report">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>财务报表</h2>
        <p class="page-description">查看企业财务状况，包括资产负债表、利润表、现金流量表等</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
        <el-button @click="handlePrint">
          <el-icon><Printer /></el-icon>
          打印报表
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 报表筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="报表类型">
          <el-select
            v-model="filterForm.reportType"
            placeholder="请选择报表类型"
            style="width: 180px"
            @change="handleReportTypeChange"
          >
            <el-option label="资产负债表" value="balance_sheet" />
            <el-option label="利润表" value="income_statement" />
            <el-option label="现金流量表" value="cash_flow" />
            <el-option label="财务分析" value="financial_analysis" />
          </el-select>
        </el-form-item>
        <el-form-item label="报表期间">
          <el-select
            v-model="filterForm.period"
            placeholder="请选择期间"
            style="width: 150px"
            @change="handlePeriodChange"
          >
            <el-option label="本月" value="current_month" />
            <el-option label="本季度" value="current_quarter" />
            <el-option label="本年度" value="current_year" />
            <el-option label="上月" value="last_month" />
            <el-option label="上季度" value="last_quarter" />
            <el-option label="上年度" value="last_year" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleGenerate">
            <el-icon><Search /></el-icon>
            生成报表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 报表内容区域 -->
    <div class="report-content">
      <!-- 资产负债表 -->
      <el-card v-if="filterForm.reportType === 'balance_sheet'" class="report-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>资产负债表</h3>
            <span class="report-date">{{ reportDate }}</span>
          </div>
        </template>
        
        <div class="balance-sheet">
          <el-row :gutter="20">
            <!-- 资产部分 -->
            <el-col :span="12">
              <div class="section-title">资产</div>
              <el-table :data="balanceSheetData.assets" border stripe>
                <el-table-column prop="item" label="项目" width="200" />
                <el-table-column prop="amount" label="金额" align="right">
                  <template #default="{ row }">
                    <span :class="{ 'negative-amount': row.amount < 0 }">
                      ¥{{ formatNumber(row.amount) }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            
            <!-- 负债和所有者权益部分 -->
            <el-col :span="12">
              <div class="section-title">负债和所有者权益</div>
              <el-table :data="balanceSheetData.liabilities" border stripe>
                <el-table-column prop="item" label="项目" width="200" />
                <el-table-column prop="amount" label="金额" align="right">
                  <template #default="{ row }">
                    <span :class="{ 'negative-amount': row.amount < 0 }">
                      ¥{{ formatNumber(row.amount) }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 利润表 -->
      <el-card v-if="filterForm.reportType === 'income_statement'" class="report-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>利润表</h3>
            <span class="report-date">{{ reportDate }}</span>
          </div>
        </template>
        
        <div class="income-statement">
          <el-table :data="incomeStatementData" border stripe>
            <el-table-column prop="item" label="项目" width="300" />
            <el-table-column prop="currentPeriod" label="本期金额" align="right" width="150">
              <template #default="{ row }">
                <span :class="{ 'negative-amount': row.currentPeriod < 0 }">
                  ¥{{ formatNumber(row.currentPeriod) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="lastPeriod" label="上期金额" align="right" width="150">
              <template #default="{ row }">
                <span :class="{ 'negative-amount': row.lastPeriod < 0 }">
                  ¥{{ formatNumber(row.lastPeriod) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="growth" label="增长率" align="right" width="120">
              <template #default="{ row }">
                <span :class="{
                  'positive-growth': row.growth > 0,
                  'negative-growth': row.growth < 0
                }">
                  {{ row.growth > 0 ? '+' : '' }}{{ row.growth.toFixed(2) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 现金流量表 -->
      <el-card v-if="filterForm.reportType === 'cash_flow'" class="report-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>现金流量表</h3>
            <span class="report-date">{{ reportDate }}</span>
          </div>
        </template>
        
        <div class="cash-flow">
          <el-table :data="cashFlowData" border stripe>
            <el-table-column prop="item" label="项目" width="300" />
            <el-table-column prop="amount" label="金额" align="right">
              <template #default="{ row }">
                <span :class="{ 'negative-amount': row.amount < 0 }">
                  ¥{{ formatNumber(row.amount) }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 财务分析 -->
      <div v-if="filterForm.reportType === 'financial_analysis'" class="financial-analysis">
        <!-- 关键指标卡片 -->
        <div class="kpi-cards">
          <el-row :gutter="20">
            <el-col :span="6" v-for="kpi in kpiData" :key="kpi.name">
              <el-card class="kpi-card">
                <div class="kpi-content">
                  <div class="kpi-icon" :class="kpi.type">
                    <el-icon><component :is="kpi.icon" /></el-icon>
                  </div>
                  <div class="kpi-info">
                    <div class="kpi-value">{{ kpi.value }}</div>
                    <div class="kpi-label">{{ kpi.name }}</div>
                    <div class="kpi-trend" :class="kpi.trend > 0 ? 'positive' : 'negative'">
                      <el-icon><component :is="kpi.trend > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                      {{ Math.abs(kpi.trend) }}%
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 图表分析 -->
        <el-row :gutter="20" class="chart-row">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>收入趋势分析</h4>
              </template>
              <div ref="revenueChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>费用结构分析</h4>
              </template>
              <div ref="expenseChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="chart-row">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>资产负债比例</h4>
              </template>
              <div ref="assetChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h4>现金流量趋势</h4>
              </template>
              <div ref="cashFlowChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Printer, Refresh, Search, TrendCharts, Money, Coin, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const revenueChartRef = ref()
const expenseChartRef = ref()
const assetChartRef = ref()
const cashFlowChartRef = ref()

// 筛选表单
const filterForm = reactive({
  reportType: 'balance_sheet',
  period: 'current_month',
  dateRange: []
})

// 计算属性 - 报表日期
const reportDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  return `${year}年${month}月`
})

// 资产负债表数据
const balanceSheetData = reactive({
  assets: [
    { item: '流动资产', amount: 0, isHeader: true },
    { item: '  货币资金', amount: 1250000 },
    { item: '  应收账款', amount: 850000 },
    { item: '  存货', amount: 650000 },
    { item: '  其他流动资产', amount: 120000 },
    { item: '流动资产合计', amount: 2870000, isTotal: true },
    { item: '非流动资产', amount: 0, isHeader: true },
    { item: '  固定资产', amount: 1800000 },
    { item: '  无形资产', amount: 300000 },
    { item: '  其他非流动资产', amount: 150000 },
    { item: '非流动资产合计', amount: 2250000, isTotal: true },
    { item: '资产总计', amount: 5120000, isGrandTotal: true }
  ],
  liabilities: [
    { item: '流动负债', amount: 0, isHeader: true },
    { item: '  应付账款', amount: 450000 },
    { item: '  短期借款', amount: 300000 },
    { item: '  应付职工薪酬', amount: 180000 },
    { item: '  其他流动负债', amount: 80000 },
    { item: '流动负债合计', amount: 1010000, isTotal: true },
    { item: '非流动负债', amount: 0, isHeader: true },
    { item: '  长期借款', amount: 800000 },
    { item: '  其他非流动负债', amount: 120000 },
    { item: '非流动负债合计', amount: 920000, isTotal: true },
    { item: '负债合计', amount: 1930000, isTotal: true },
    { item: '所有者权益', amount: 0, isHeader: true },
    { item: '  实收资本', amount: 2000000 },
    { item: '  未分配利润', amount: 1190000 },
    { item: '所有者权益合计', amount: 3190000, isTotal: true },
    { item: '负债和所有者权益总计', amount: 5120000, isGrandTotal: true }
  ]
})

// 利润表数据
const incomeStatementData = ref([
  { item: '一、营业收入', currentPeriod: 2500000, lastPeriod: 2200000, growth: 13.64 },
  { item: '减：营业成本', currentPeriod: 1500000, lastPeriod: 1350000, growth: 11.11 },
  { item: '    税金及附加', currentPeriod: 45000, lastPeriod: 42000, growth: 7.14 },
  { item: '    销售费用', currentPeriod: 180000, lastPeriod: 165000, growth: 9.09 },
  { item: '    管理费用', currentPeriod: 220000, lastPeriod: 210000, growth: 4.76 },
  { item: '    财务费用', currentPeriod: 35000, lastPeriod: 28000, growth: 25.00 },
  { item: '二、营业利润', currentPeriod: 520000, lastPeriod: 405000, growth: 28.40 },
  { item: '加：营业外收入', currentPeriod: 15000, lastPeriod: 12000, growth: 25.00 },
  { item: '减：营业外支出', currentPeriod: 8000, lastPeriod: 5000, growth: 60.00 },
  { item: '三、利润总额', currentPeriod: 527000, lastPeriod: 412000, growth: 27.91 },
  { item: '减：所得税费用', currentPeriod: 131750, lastPeriod: 103000, growth: 27.91 },
  { item: '四、净利润', currentPeriod: 395250, lastPeriod: 309000, growth: 27.91 }
])

// 现金流量表数据
const cashFlowData = ref([
  { item: '一、经营活动产生的现金流量', amount: 0, isHeader: true },
  { item: '  销售商品、提供劳务收到的现金', amount: 2650000 },
  { item: '  收到的税费返还', amount: 15000 },
  { item: '  收到其他与经营活动有关的现金', amount: 85000 },
  { item: '经营活动现金流入小计', amount: 2750000, isSubtotal: true },
  { item: '  购买商品、接受劳务支付的现金', amount: 1680000 },
  { item: '  支付给职工以及为职工支付的现金', amount: 420000 },
  { item: '  支付的各项税费', amount: 185000 },
  { item: '  支付其他与经营活动有关的现金', amount: 125000 },
  { item: '经营活动现金流出小计', amount: 2410000, isSubtotal: true },
  { item: '经营活动产生的现金流量净额', amount: 340000, isTotal: true },
  { item: '二、投资活动产生的现金流量', amount: 0, isHeader: true },
  { item: '  处置固定资产收到的现金', amount: 25000 },
  { item: '  购建固定资产支付的现金', amount: 180000 },
  { item: '投资活动产生的现金流量净额', amount: -155000, isTotal: true },
  { item: '三、筹资活动产生的现金流量', amount: 0, isHeader: true },
  { item: '  取得借款收到的现金', amount: 200000 },
  { item: '  偿还债务支付的现金', amount: 150000 },
  { item: '  分配股利支付的现金', amount: 100000 },
  { item: '筹资活动产生的现金流量净额', amount: -50000, isTotal: true },
  { item: '四、现金及现金等价物净增加额', amount: 135000, isGrandTotal: true }
])

// KPI数据
const kpiData = ref([
  {
    name: '资产收益率',
    value: '7.72%',
    trend: 2.5,
    icon: 'TrendCharts',
    type: 'primary'
  },
  {
    name: '净利润率',
    value: '15.81%',
    trend: 3.2,
    icon: 'Money',
    type: 'success'
  },
  {
    name: '流动比率',
    value: '2.84',
    trend: -1.2,
    icon: 'Coin',
    type: 'warning'
  },
  {
    name: '资产负债率',
    value: '37.70%',
    trend: -0.8,
    icon: 'TrendCharts',
    type: 'info'
  }
])

// 方法
const handleReportTypeChange = () => {
  if (filterForm.reportType === 'financial_analysis') {
    nextTick(() => {
      initCharts()
    })
  }
}

const handlePeriodChange = () => {
  handleGenerate()
}

const handleDateChange = () => {
  handleGenerate()
}

const handleGenerate = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('报表生成成功')
  }, 1000)
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handlePrint = () => {
  window.print()
}

const handleRefresh = () => {
  handleGenerate()
}

// 初始化图表
const initCharts = () => {
  initRevenueChart()
  initExpenseChart()
  initAssetChart()
  initCashFlowChart()
}

// 收入趋势图表
const initRevenueChart = () => {
  if (!revenueChartRef.value) return
  
  const chart = echarts.init(revenueChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}万'
      }
    },
    series: [{
      name: '收入',
      type: 'line',
      smooth: true,
      data: [180, 195, 210, 225, 240, 250],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ])
      }
    }]
  }
  chart.setOption(option)
}

// 费用结构图表
const initExpenseChart = () => {
  if (!expenseChartRef.value) return
  
  const chart = echarts.init(expenseChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c}万 ({d}%)'
    },
    series: [{
      name: '费用结构',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [
        { value: 150, name: '营业成本' },
        { value: 22, name: '管理费用' },
        { value: 18, name: '销售费用' },
        { value: 3.5, name: '财务费用' },
        { value: 4.5, name: '税金及附加' }
      ],
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {d}%'
      }
    }]
  }
  chart.setOption(option)
}

// 资产负债图表
const initAssetChart = () => {
  if (!assetChartRef.value) return
  
  const chart = echarts.init(assetChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c}万 ({d}%)'
    },
    series: [{
      name: '资产负债',
      type: 'pie',
      radius: '60%',
      data: [
        { value: 287, name: '流动资产' },
        { value: 225, name: '非流动资产' },
        { value: 101, name: '流动负债' },
        { value: 92, name: '非流动负债' },
        { value: 319, name: '所有者权益' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  chart.setOption(option)
}

// 现金流量图表
const initCashFlowChart = () => {
  if (!cashFlowChartRef.value) return
  
  const chart = echarts.init(cashFlowChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['经营活动', '投资活动', '筹资活动']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}万'
      }
    },
    series: [{
      name: '现金流量',
      type: 'bar',
      data: [
        { value: 34, itemStyle: { color: '#67C23A' } },
        { value: -15.5, itemStyle: { color: '#F56C6C' } },
        { value: -5, itemStyle: { color: '#E6A23C' } }
      ],
      barWidth: '60%'
    }]
  }
  chart.setOption(option)
}

// 工具方法
const formatNumber = (num) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(num)
}

// 生命周期
onMounted(() => {
  if (filterForm.reportType === 'financial_analysis') {
    nextTick(() => {
      initCharts()
    })
  }
})
</script>

<style scoped>
.financial-report {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.report-content {
  margin-top: 20px;
}

.report-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.report-date {
  color: #909399;
  font-size: 14px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 2px solid #409EFF;
}

.negative-amount {
  color: #F56C6C;
}

.positive-growth {
  color: #67C23A;
}

.negative-growth {
  color: #F56C6C;
}

.financial-analysis {
  margin-top: 20px;
}

.kpi-cards {
  margin-bottom: 20px;
}

.kpi-card {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.kpi-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.kpi-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.kpi-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.kpi-icon.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.kpi-icon.success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.kpi-icon.warning {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.kpi-icon.info {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.kpi-info {
  flex: 1;
}

.kpi-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.kpi-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.kpi-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.kpi-trend.positive {
  color: #67C23A;
}

.kpi-trend.negative {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  width: 100%;
  height: 320px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .financial-report {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .balance-sheet .el-col {
    margin-bottom: 20px;
  }
  
  .kpi-cards .el-col {
    margin-bottom: 16px;
  }
  
  .chart-row .el-col {
    margin-bottom: 20px;
  }
  
  .chart-card {
    height: 300px;
  }
  
  .chart-container {
    height: 220px;
  }
}

@media print {
  .page-header,
  .filter-card {
    display: none;
  }
  
  .report-card {
    break-inside: avoid;
    margin-bottom: 30px;
  }
}
</style>